package mobilesearch.thread;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import android.database.Cursor;
import mobilesearch.data.SmsData;
import mobilesearch.ui.BroadcastCommand;

import java.util.ArrayList;

public class SmsSearchThread extends Thread {

	private static final String TAG = "SmsSearchThread";

	private static final String SMS_DB = "content://sms";

	private ContentResolver resolver;
	private Context context;

	private String smsId;
	private String smsPerson;
	private String smsBody;

	public SmsSearchThread(Context context, ContentResolver resolver) {
		super();
		this.context = context;
		this.resolver = resolver;
	}

	@Override
	public void run() {
		super.run();
		Log.i(TAG, "run()");

		ArrayList<SmsData> smsList = new ArrayList<SmsData>();
		try {
			Cursor dbCursor = this.resolver.query(Uri.parse(SMS_DB), null,null, null, null);
			if (dbCursor.moveToFirst()) {
				Log.i(TAG, "dbCursor.moveToFirst()");
				do {
					SmsData data = new SmsData();

					int idIndex = dbCursor.getColumnIndex("_id");
					this.smsId = dbCursor.getString(idIndex);
					data.setSmsId(this.smsId);
					Log.i(TAG, this.smsId);

					int personIndex = dbCursor.getColumnIndex("person");
					this.smsPerson = dbCursor.getString(personIndex);
					if (this.smsPerson == null) {
						this.smsPerson = "no person";
					}
					data.setSmsPerson(this.smsPerson);
					Log.i(TAG, this.smsPerson);

					int bodyIndex = dbCursor.getColumnIndex("body");
					this.smsBody = dbCursor.getString(bodyIndex);
					data.setSmsBody(this.smsBody);
					Log.i(TAG, this.smsBody);

					smsList.add(data);

				} while (dbCursor.moveToNext());
			}
		} catch (Exception exception) {
			Log.i(TAG, exception.toString());
		}

		// broadcast the data
		if(!smsList.isEmpty()){
			Intent smsIntent = new Intent(BroadcastCommand.SEARCH_SMS);
			smsIntent.putParcelableArrayListExtra(BroadcastCommand.SEARCH_SMS,smsList);
			this.context.sendBroadcast(smsIntent);	
		}

	}// end run()
}
